package com.wsgxj.util;

import com.wsgxj.controller.UploadController;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 提供模板下载的工具类
 */
public class TemplateUtil {
    private static final Log logger = LogFactory.getLog(UploadController.class);

    public static void getTemplate(HttpServletResponse response,String fileName) {
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            Resource resource = new DefaultResourceLoader().getResource("classpath:/META-INF/resources/static/config/"+fileName+ ".xlsx");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1)
                    + ".xlsx");
            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            response.setContentType("");
            response.setHeader("", "");
            logger.error("下载批量上传模板文件错误", e);
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                logger.error("下载批量上传模板文件错误", e);
            }
        }
    }
}
